<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>掘金上的promise https://juejin.cn/post/7038371452084551694</title>
	</head>
	<body>
		<script>
			Promise.myResolve = function(value){
				//是promise实例直接返回即可
				if(value && typeof value === 'object' && (value instanceof Promise)){
					return value
				}
				//其他情况一律在通过promise包装
				return new Promise((resolve)=>{
					resolve(value)
				})
			}
			Promise.myReject = function(value){
				return new Promise((_,reject) => {
					reject(value)
				})
			}
			const p = Promise.all([p1,p2,p3])
			Promise.myAll = (promises) => {
				return new Promise((resolved,rejected) => {
					//计数器
					let count = 0
					//存放结果
					let result = []
					const len = promises.length
					if(len === 0) {
						return resolved([])
					}
					promises.forEach((p.i)=>{
						//注意有的数组项有可能不是Promise,需要转换一下
						Promise.reslove(p).then((res) => {
							count += 1
							result[i] = res
							if(count === len){
								resolved(result)
							}
						}).catch(rejected)
					})
				})
			}
			const p1 = Promise.allSettled([p1,p2,p3,p4])
			Promise.myAllsettled = (promises) => {
				return new Promise(resovled,rejected) => {
					const len = promises.length
					let count = 0
					let result = []
					//如果数组是空的话直接返回空数据
					if(len === 0){
						return rejected([])
					}
					promises.forEach((p,i) =>{
						Promise.resolve(p).then((res)=>{
							count += 1
							//成功属性设置
							result[i] = {
								status: 'fulfilled',
								value:res
							}
							if(count === len){
								resovled(result)
							}
						}).catch((err)=>{
							count += 1
							//失败属性设置
							result[i] = {
								status: 'rejected',
								reason: err
							}
							if(count === len) {
								resolved(result)
							}
						})
					})
				}
			}
		</script>
	</body>
</html>
